import React from 'react';
import { PermissionsAndroid, Permission } from 'react-native';
import Log from '../common/log';
import PortraitAlert from '../components/Alert/PortraitAlert';

import { DEVICE_BRAND_VIVO } from '../constant';
import { modalClose, modalOpen } from './global';
import { systemUtil } from './native';

const PERMISSION_DESC = {
  [PermissionsAndroid.PERMISSIONS.CAMERA]: '相机',
  [PermissionsAndroid.PERMISSIONS.RECORD_AUDIO]: '录音',
  [PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE]: '存储'
};

const getLocalPermission = (permission: Permission): Promise<string> => {
  return new Promise(
    async (resolve, reject): Promise<void> => {
      let haveGetPermission = false;
      const timer = setTimeout((): void => {
        if (!haveGetPermission) {
          resolve(PERMISSION_DESC[permission]);
        }
      }, 2000);

      const res = await PermissionsAndroid.request(permission);

      haveGetPermission = true;
      clearTimeout(timer);

      if (res !== 'granted') {
        resolve(PERMISSION_DESC[permission]);
      }
      resolve('');
    }
  );
};

export const getPermission = (): Promise<any> => {
  return new Promise(
    async (resolve, reject): Promise<void> => {
      // vivo 权限申请特殊，通过下面的方法调用的时候，没有任何回调，手动调用onResume方法，才有回调
      // 测试发现，vivo的存储权限不需要手动获取，所以直接通过
      if (systemUtil.getDeviceProduct() === DEVICE_BRAND_VIVO) {
        resolve();
      }
      try {
        let permissions: string[] = [];

        let res = await getLocalPermission(
          PermissionsAndroid.PERMISSIONS.READ_PHONE_STATE
        );

        res = await getLocalPermission(PermissionsAndroid.PERMISSIONS.CAMERA);
        if (res !== '') {
          permissions = [res];
        }

        res = await getLocalPermission(
          PermissionsAndroid.PERMISSIONS.RECORD_AUDIO
        );
        if (res !== '') {
          permissions = [res];
        }

        res = await getLocalPermission(
          PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE
        );
        if (res !== '') {
          permissions = [res];
        }

        if (permissions.length > 0) {
          reject(permissions.join(','));
        }
        resolve();
      } catch (e) {
        Log.i('GetPermissionFailed', JSON.stringify({ error: e }));
        reject();
      }
    }
  );
};

export const openSet = (): void => {
  modalClose();
  setTimeout((): void => {
    systemUtil.openSetting((): void => {});
  });
  setTimeout((): void => {
    systemUtil.exitApp();
  }, 1000);
};

export const forceOpenPermission = (permissionsDesc: string): void => {
  modalOpen({
    Type: (): React.ReactElement => (
      <PortraitAlert
        title="权限申请"
        sureDesc="去设置"
        subTitle={`为了完整的体验在线课堂，我们需要使用${permissionsDesc}等权限！${'\n'}在设置-应用-蜜蜂小班-权限管理-开启${permissionsDesc}权限，以正常使用蜜蜂小班课功能`}
        sureAction={openSet}
      />
    ),
    needBack: true
  });
};

export const openPermissionModal = (
  permissionsDesc: string,
  cancel?: () => void,
  isForce?: boolean
): void => {
  modalOpen({
    Type: (): React.ReactElement => (
      <PortraitAlert
        title="权限申请"
        sureDesc="去设置"
        subTitle={`在设置-应用-蜜蜂小班-权限管理-开启${permissionsDesc}权限，以正常使用蜜蜂小班功能`}
        sureAction={openSet}
        cancelAction={(): void => {
          if (isForce) {
            forceOpenPermission(permissionsDesc);
            return;
          }
          if (cancel) {
            cancel();
          }
          modalClose();
        }}
      />
    ),
    needBack: true
  });
};
